﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using BYRForum.Binding.Thread;
using BYRBBS.Model;
using BYRBBS.Util;
using System.Diagnostics;
using BYRBBS.MyDebug;

namespace BYRForum
{
    public partial class ThreadsListPage : PhoneApplicationPage
    {

        ApplicationBarIconButton BarButtonPreviousPage;
        ApplicationBarIconButton BarButtonNextPage;
        ApplicationBarIconButton BarButtonNewThread;
        ApplicationBarIconButton BarButtonRefresh;

        bool if_loaded = false;
        int total_page = 1;
        int current_page = 1;

        public ThreadsListPage()
        {
            InitializeComponent();
            this.SetValue(SystemTray.IsVisibleProperty, !(bool)this.GetValue(SystemTray.IsVisibleProperty));
           // ThreadsListBox.ItemsSource = App.ThreadsList.Items;

            BarButtonPreviousPage = this.ApplicationBar.Buttons[0] as ApplicationBarIconButton;
            BarButtonNewThread = this.ApplicationBar.Buttons[1] as ApplicationBarIconButton;
            BarButtonRefresh = this.ApplicationBar.Buttons[2] as ApplicationBarIconButton;
            BarButtonNextPage = this.ApplicationBar.Buttons[3] as ApplicationBarIconButton;


            BarButtonNewThread.IsEnabled = false;
            BarButtonPreviousPage.IsEnabled = false;
            BarButtonNextPage.IsEnabled = false;
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!if_loaded)
            {
                App.ThreadsList.Items.Clear();
                ThreadsListBox.ItemsSource = App.ThreadsList.Items;
                String myRequestUrl = ByrApi.apiUrl + "/board/" + App.TempBoardItem.Name + ByrApi.Encode + ByrApi.appkey;
                RequestState state = new RequestState();
                HttpUtil.HttpGetWithParam(state, myRequestUrl, HttpWebRequset_ThreadsList_Callback);//发送请求
                progressBarWait.Visibility = Visibility.Visible;
                if_loaded = true;
            }
            
        }

        private void ApplicationTitle_Loaded(object sender, RoutedEventArgs e)
        {
            string BoardName = String.Format("{0}", NavigationContext.QueryString["BoardName"]);
            if (BoardName == "C/C  程序设计语言")
                PageTitle.Text = "C/C++程序设计语言";
            else
                PageTitle.Text = BoardName;
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ThreadsItem data = (sender as ListBox).SelectedItem as ThreadsItem;
            ListBoxItem selectedItem = (sender as ListBox).ItemContainerGenerator.ContainerFromItem(data) as ListBoxItem;

            int nSelect = (sender as ListBox).SelectedIndex;  //选择的项保存在 nSelect中
            //防止出错。
            if (-1 == nSelect)
            {
                return;
            }
            App.TempThreadItem = data;
            NavigationService.Navigate(new Uri("/BYRForum;component/ThreadsDetailPage.xaml", UriKind.Relative));
            (sender as ListBox).SelectedIndex = -1;  //最后设置整个ListBox控件选择为空，否则下次改变时获取的仍然是上次的值

        }

        private void HttpWebRequset_ThreadsList_Callback(IAsyncResult asynchronousResult)
        {
            try
            {
                //网络有错误将会在这里抛出异常
                string result = HttpUtil.ReadToEndWithParam(asynchronousResult);
                DebugInfo.writeXml(result);
                string ErrorInfo;
                BoardThread Threads = ParseUtil.ParseXml<BoardThread>(result, out ErrorInfo);
                current_page =Convert.ToInt32( Threads.Pag.Page_current_count);
                total_page =Convert.ToInt32( Threads.Pag.Page_all_count);
                this.Dispatcher.BeginInvoke((Action)(() =>
                {
                    progressBarWait.Visibility = Visibility.Collapsed;
                    App.ThreadsList.LoadData(Threads.ArticleHeadItems);
                    ShowApplicationBarState(current_page,total_page);
                }));
            }
            catch
            {
                Debug.WriteLine("Error");
                this.Dispatcher.BeginInvoke(() =>
                {
                    progressBarWait.Visibility = Visibility.Collapsed;
                });
                //这里处理异常，可以在界面上抛出messagebox
            }
        }
        protected void GoToPage(int pageNum)
        {
            String myRequestUrl = ByrApi.apiUrl + "/board/" + App.TempBoardItem.Name + ByrApi.Encode + ByrApi.appkey + "page=" + pageNum.ToString();
            RequestState state = new RequestState();
            HttpUtil.HttpGetWithParam(state, myRequestUrl, HttpWebRequset_ThreadsList_Callback);//发送请求
            progressBarWait.Visibility = Visibility.Visible;
        }
        protected void ShowApplicationBarState(int current,int total)
        {
            BarButtonNewThread.IsEnabled = true;
            BarButtonPreviousPage.IsEnabled = true;
            BarButtonRefresh.IsEnabled = true;
            BarButtonNextPage.IsEnabled = true;
            if (current == 1)
            {
                BarButtonPreviousPage.IsEnabled = false;
            }
            if (current == total)
            {
                BarButtonNextPage.IsEnabled = false;
            }
        }
        protected void DisableApplicationBar()
        {
            BarButtonNewThread.IsEnabled = false;
            BarButtonPreviousPage.IsEnabled = false;
            BarButtonNextPage.IsEnabled = false;
        }

        #region ApplicationBar Button
        private void NewArticle_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri(String.Format("/BYRForum;component/NewThread.xaml?BoardName={0}", PageTitle.Text), UriKind.Relative));
        }

        private void PreviousPage_Click(object sender, EventArgs e)
        {
            DisableApplicationBar();
            GoToPage(--current_page);
        }

        private void NextPage_Click(object sender, EventArgs e)
        {
            DisableApplicationBar();
            GoToPage(++current_page);
        }
        #endregion

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
            App.ThreadsList.Items.Clear();
        }

        private void Refresh_Click(object sender, EventArgs e)
        {
            GoToPage(current_page);
        }
    }
}